﻿using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using WebCore.ConfigHelper;

namespace WebCore.Repository
{
    public abstract class DapperRepository<TEntity, TKey> : IRepository<TEntity, TKey>
    {
        public string TableName => typeof(TEntity).Name;
        private static string _connectionString;
        private static readonly object obj = new object();
        /// <summary>
        /// 解密方法
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        protected virtual string Decrypt(string content) {
            return content;
        }
        protected abstract IDbConnection GetDbConnection();
        /// <summary>
        /// 获取连接串
        /// </summary>
        /// <returns></returns>
        public virtual string ConnectionString()
        {
            if (_connectionString == null) {
                lock (obj) {
                    if (_connectionString == null) {
                        var server = AppsettingsConfigHelper.GetSectionValue("ConnectionStrings:DefaultConnection:server");
                        var port = AppsettingsConfigHelper.GetSectionValue("ConnectionStrings:DefaultConnection:port");
                        var database = AppsettingsConfigHelper.GetSectionValue("ConnectionStrings:DefaultConnection:database");
                        var uid = AppsettingsConfigHelper.GetSectionValue("ConnectionStrings:DefaultConnection:uid");
                        var password = AppsettingsConfigHelper.GetSectionValue("ConnectionStrings:DefaultConnection:password");
                        _connectionString = $"server={server};port={port};database={database};uid={uid};password={Decrypt(password)};Allow User Variables=True;Charset=utf8mb4;";
                    }
                }
            }
            return _connectionString;
        }

        public TKey Create(TEntity entity)
        {
            throw new NotImplementedException();
        }

        public int Delete(TKey id)
        {
            throw new NotImplementedException();
        }

        public int DeleteBatch(List<TKey> ids)
        {
            throw new NotImplementedException();
        }

        public TEntity GetByKey(TKey id)
        {
            throw new NotImplementedException();
        }

        public int Update(TEntity entity)
        {
            throw new NotImplementedException();
        }
        
        public List<TEntity> Query(string cols,string where,object obj = null)
        {
            string sql = $"SELECT {cols} FROM {TableName}  WHERE {where};";
            using IDbConnection conn = GetDbConnection();
            return conn.Query<TEntity>(sql,obj).ToList();
        }
    }
}
